/**
 * 动态插入Script
 */

function loadedUeditor () {
  // 检查脚本是否下载成功
  return window.UE
}

const dynamicLoadScript = (src) => {
  const origin = window.location.origin
  const pathname = window.location.pathname
  const BASE_URL = origin + pathname
  const RESOURCE_URL = `${BASE_URL}static/ueditor/${src}`

  return new Promise((resolve, reject) => {
    const existingScript = document.getElementById(RESOURCE_URL)

    // 不存在创建
    if (!existingScript) {
      const script = document.createElement('script')
      script.src = RESOURCE_URL
      script.id = RESOURCE_URL
      document.body.appendChild(script)
      const onEnd = 'onload' in script ? stdOnEnd : ieOnEnd
      onEnd(script)
    } else {
      if (loadedUeditor()) {
        resolve(existingScript)
      } else {
        reject(new Error('window.UE not defined!'))
      }
    }

    function stdOnEnd (script) {
      script.onload = function () {
        this.onerror = this.onload = null
        resolve(script)
      }
      script.onerror = function () {
        this.onerror = this.onload = null
        reject(new Error('Failed to load' + RESOURCE_URL))
      }
    }

    function ieOnEnd (script) {
      script.onreadystatechange = function () {
        if (this.readyState !== 'complete' && this.readyState !== 'loaded') return
        this.onreadystatechange = null
        resolve(script)
      }
    }

  })
}

export default dynamicLoadScript
